//
// Created by 廖海龙 on 2025/4/15.
//

#include "HelloHeader.hpp"

std::string HelloHeader::toLower(const std::string &str)
{
    std::string res = str;
    std::transform(res.begin(), res.end(), res.begin(), ::tolower);
    return res;
}

std::string
HelloHeader::buildQueryString(const std::unordered_map<std::string, std::string> &_headers)
{
    std::string result;
    for (const auto &pair: _headers)
    {
        if (!result.empty())
        {
            result += "&";
        }

        result += pair.first + "=";

        const std::string &val = pair.second;

        // 判断是否为纯数字
        bool isNumeric = !val.empty() && std::all_of(val.begin(), val.end(), ::isdigit);

        if (isNumeric)
        {
            result += val;
        } else
        {
            result += "\"" + val + "\"";
        }
    }
    return result;
}

bool HelloHeader::endsWith(const std::string &str, const std::string &suffix)
{
    if (suffix.size() > str.size()) return false;
    return std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
}

bool HelloHeader::isDigits(const std::string &str)
{
    return !str.empty() && std::all_of(str.begin(), str.end(), ::isdigit);
}

std::string HelloHeader::getResponseHeader(const std::shared_ptr<HelloRange> &range,
                                           int64_t contentLength, const std::string &type)
{
    int64_t start_int64 = range->start;
    int64_t end_int64 = range->end;
    if (end_int64 < 0)
    {
        end_int64 = contentLength - 1; // 处理end=-1的情况
    }
    std::string start = std::to_string(start_int64);
    std::string end = std::to_string(end_int64);
    std::string length = std::to_string(contentLength);
    std::string headers;
    if (range->available())
    {
        std::string currLen = std::to_string(end_int64 - start_int64 + 1); // 返回实际字节量
        headers += "HTTP/1.1 206 Partial Content\r\n";
        headers += "Content-Type: " + type + "\r\n";
        headers += "Content-Length: " + currLen + "\r\n";
        headers += "Content-Range: bytes " + start + "-" + end + "/" + length + "\r\n";
        headers += "Accept-Ranges: bytes\r\n";
        headers += "Connection: keep-alive\r\n";
        headers += "\r\n";
    } else
    {
        headers += "HTTP/1.1 200 OK\r\n";
        headers += "Content-Type: " + type + "\r\n";
        headers += "Content-Length: " + length + "\r\n";
        headers += "Accept-Ranges: bytes\r\n";
        headers += "Connection: keep-alive\r\n";
        headers += "\r\n";
    }
    return headers;
}

std::string HelloHeader::trim(const std::string &s)
{
    size_t start = s.find_first_not_of(" \t\r\n");
    size_t end = s.find_last_not_of(" \t\r\n");
    return (start == std::string::npos || end == std::string::npos) ? "" : s.substr(start, end - start + 1);
}